package cc.decat.escript.object;

import java.util.ArrayList;
import java.util.List;

public class ESListObject extends ESObject {

    private List<ESObject> list;

    public ESListObject() {
        super(ESListType.getInstance());
        this.list = new ArrayList<>();
    }

    public List<ESObject> getList() {
        return list;
    }
}

class ESListType extends ESType {

    private static final ESListType instance = new ESListType();

    public static ESListType getInstance() {
        return instance;
    }

    private ESListType() {
        super("List");
    }


    @Override
    public ESObject len(ESObject x) {
        ESListObject esListObj = (ESListObject) x;
        return ESIntegerObject.fromValue((long) esListObj.getList().size());
    }

    @Override
    public ESObject getSubscr(ESObject lhs, ESObject rhs) {
        ESListObject lhsObj = (ESListObject) lhs;
        ESIntegerObject rhsObj = (ESIntegerObject) rhs;
        return lhsObj.getList().get((int) rhsObj.getValue());
    }

    @Override
    public void setSubscr(ESObject lhs, ESObject mhs, ESObject rhs) {
        ESListObject lhsObj = (ESListObject) lhs;
        ESIntegerObject mhsObj = (ESIntegerObject) mhs;
        lhsObj.getList().set((int) mhsObj.getValue(), rhs);
    }

    @Override
    public ESObject str(ESObject x) {
        List<ESObject> list = ((ESListObject) x).getList();
        if(list.size() == 0) {
            return ESStringObject.fromValue("[]");
        } else if(list.size() == 1) {
            return ESStringObject.fromValue(("[" + ((ESStringObject)list.get(0).getType().str(list.get(0))).getStr() + "]"));
        } else {
            StringBuilder sb = new StringBuilder("[");
            for(int i = 0; i < list.size() - 1; i++) {
                sb.append(((ESStringObject)list.get(i).getType().str(list.get(i))).getStr());
                sb.append(", ");
            }
            sb.append(((ESStringObject)list.get(list.size() - 1).getType().str(list.get(list.size() - 1))).getStr());
            sb.append("]");
            return ESStringObject.fromValue((sb.toString()));
        }
    }
}
